package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.LogoutMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

import java.util.Objects;

/**
 * @author zp
 * @version 1.0
 * @description: 处理消息LogoutMessage
 * @date 2023/4/6 18:29
 */
@Slf4j
public class LogoutMessageHandler extends SimpleChannelInboundHandler<LogoutMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LogoutMessage msg) throws Exception {
        Channel channel = ctx.channel();
        String userName = msg.getUserName();
        GlobalContent globalContent = GlobalContent.getInstance();
        UserSession userSession = globalContent.getSession(userName);
        log.debug("登出的消息：{}",msg);
        if(Objects.isNull(userSession)){
            SystemMessage.sendFailMessage(SystemMessageType.LOG_OUT_FAIL,ctx);
        }else {
            User user = userSession.getUser();
            // 解绑定
            globalContent.unbind(user.getUserId(),user.getUserName());
            // 删除channel里面的数据
            NettyChannelUtil.removeUserSession(channel);
            ctx.channel().writeAndFlush(msg);
        }
    }
}
